package com.itzhigui.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义拦截器
 *
 * @author java1412
 * @since 2024-04-12 10:08:33
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断当前是否登录，如果登录就放行，如果没有登录就返回一个json
        HttpSession session = request.getSession();
        Object loginUser = session.getAttribute("loginUser");
        // 判断
        if (null == loginUser) {
            // 未登录
            System.out.println("未登录，不能访问后续的接口");
            // 定义返回的json
            response.setContentType("text/html;charset=UTF-8");
            Map<String, Object> map = new HashMap<>();
            map.put("msg", "未登录");
            ObjectMapper om = new ObjectMapper();
            //  om.writeValueAsString()：将对象转成json串
            String json = om.writeValueAsString(map);
            PrintWriter out = response.getWriter();
            out.write(json);
            out.flush();
            out.close();
            return false;
        } else {
            // 已登录
            System.out.println("已登录，可以访问后续的接口");
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
